﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DataLib.Accounts.Bus;
using System.Web.Script.Serialization;
using System.Text;
using log4net;


namespace Ewts.ashx
{
    /// <summary>
    /// outStorageUpdate 的摘要说明
    /// </summary>
    public class outStorageUpdate : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {

            string strjson = "0";

            if (context.Request["otype"] != null && context.Request["otype"].ToString().Trim() == "delBar")
            {
                string barvalue = context.Request["barvalue"];
                string operman = context.Request["oper"];
                string outid = context.Request["outid"];
                DelBarCode(barvalue, operman, outid);
            }

            //获取出库单号
            if (context.Request["outtype"] != null && context.Request["outtype"].ToString().Trim() != "")
            {
                strjson = GetOutStorageNo(context.Request["outtype"], context.Request["outid"]);
            }


            //验证条码是否合法，返回JSON数组
            if (context.Request["barcode"] != null && context.Request["barcode"].ToString().Trim() != "")
            {
                string par_barcode = context.Request["barcode"].ToString().Trim();
                string par_otype = context.Request["otype"].ToString().Trim();
                string par_input = context.Request["barbelong_old"].ToString().Trim();
                string par_output = context.Request["bargraphic_old"].ToString().Trim();
                string oldload = context.Request["oldload"].ToString().Trim();
                strjson = OutBarCodeConfirm(par_barcode, par_otype, par_input, par_output, oldload);
            }

            //出库事件提交
            if (context.Request["outbar"] != null)
            {

                strjson = SaveOutStorage(
                            context.Request["barids"],
                            context.Request["outid"],
                            context.Request["outno"],
                            context.Request["oper"],
                            context.Request["belong"],
                            context.Request["graphic"],
                            context.Request["ConsumMan"],
                            context.Request["saleno"],
                            context.Request["docusm"],
                            context.Request["otype"],
                            context.Request["month"],
                            context.Request["remark"]).ToString();

            }

            context.Response.Write(strjson);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

             /// <summary>
        /// 提交以后的出库操作
        /// </summary>
        /// <param name="arrbar">所有条形码</param>
        /// <param name="otype">出库方式</param>
        /// <param name="belong">归属地</param>
        /// <param name="consumman">领料人</param>
        /// <param name="graphic">处理地</param>
        /// <param name="oper">操作人员</param>
        /// <param name="outno">出库编号</param>
        /// <returns></returns>
        public string AddOutStorage(string[] arrbar, string otype, string outno, string oper, string belong, string graphic, string consumman,string month)
        {

            //取得barcode的Model
            //GetModelByCode(arrbar[0]);
            int loadid = 0;
            string belongcity = belong;
            string graphiccity = graphic;
            int cjoid = 0;
            bool nvflag = true;

            for (int i = 0; i < arrbar.Length; i++)
            {
                if (arrbar[i].Trim() != "")
                {
                    DataLib.Model.BarCode bmodel = new DataLib.BLL.BarCode().GetModelByCode(arrbar[i]);
                    if (bmodel.loadnumid == 0)
                    {
                        //loadid = (int)bmodel.loadnumid;
                        nvflag = nvflag && false;
                    }
                    else if (bmodel.loadnumid != 0)
                    {
                        loadid = (int)bmodel.loadnumid;
                        cjoid = (int)bmodel.cjoid;
                        nvflag = nvflag && true;
                        break;
                    }
                }
            }

            DataLib.BLL.OutStorage oBll = new DataLib.BLL.OutStorage();
            //插入outstorage
            DataLib.Model.OutStorage oModel = new DataLib.Model.OutStorage();
            //User curUser = new User();
            //curUser = (User)Session["UserInfo"];

            //出库操作人员
            oModel.Operator = oper;
            oModel.outStorageDate = DateTime.Now;
            oModel.ConsumMan = consumman;
            oModel.clearmonth = month;
            User curUser = new User(oper);
            if (curUser != null)
            {
                if (belongcity != null && belongcity.Trim() != "0")
                    belongcity = curUser.CompanyCity;
                else if (graphiccity != null && graphiccity.Trim() != "0")
                    graphiccity = curUser.CompanyCity;
            }

            if (nvflag == true)
            {
                oModel.VLoadNum = new DataLib.BLL.LoadNum().GetModel(loadid).loadnum;

            }
            //else
            //{
            //    oModel.VLoadNum = Code.NumGeneration.GetSerialNum("XN", "VLoadNum");//虚拟Load号
            //}

            oModel.outStorageType = otype;
            oModel.outStorageNo = outno;

            //出库编号
            //if (oBll.isOutNo(outno) == false)
            //{
            //    oModel.outStorageNo = outno;
            //}
            //else
            //{
            //    oModel.outStorageNo = Code.NumGeneration.GetSerialNum(outno.Substring(0, 1), "OutCode");
            //}
            switch(oModel.outStorageType)
            {
                case "4":
                    oModel.status = 0;
                    break;
                case "9":
                    oModel.status = 0;
                    break;
                case "5":
                    oModel.status = 3;
                    break;
                default:
                    oModel.status = 1;
                    break;
            }

            oModel.belogarea = belongcity;
            oModel.graphicCity = graphiccity;
            oModel.id = oBll.Add(oModel);
            //if (int.Parse(flag) <= 0)
            //    return flag;
            //修改barcode数据
            decimal onwt = 0;
            for (int i = 0; i < arrbar.Length; i++)
            {
                if (arrbar[i] != null && arrbar[i].ToString().Trim() != "")
                    onwt += SetBarCodeOut(oModel, arrbar[i]);
            }

            //出库单重量更新
            oModel.totalWeight = onwt;
            new DataLib.BLL.OutStorage().Update(oModel);

            if ((cjoid != 0) && oModel.outStorageType == "2")
            {
                DataLib.Model.Cjo cmodel = new DataLib.BLL.Cjo().GetModel(cjoid);
                cmodel.status = 5;
                new DataLib.BLL.Cjo().Update(cmodel);
            }
            return oModel.id.ToString();

        }

        public decimal SetBarCodeOut(DataLib.Model.OutStorage oModel, string barcode)
        {
            //取得barcode的Model

            DataLib.Model.BarCode bModel = new DataLib.BLL.BarCode().GetModelByCode(barcode);
            //出库方式
            switch (bModel.status)
            {
                case 3:
                    bModel.status = 4;
                    break;
                case 5:
                    bModel.status = 6;
                    break;
                case 1:
                    bModel.status = 2;
                    break;
                case 7:
                    bModel.status = 8;
                    break;
                case 9:
                    bModel.status = 10;
                    break;
                default:
                    bModel.status = -1;
                    break;
            }
            bModel.loadnumv = oModel.VLoadNum;
            bModel.OutStrorageID = oModel.id;

            if (new DataLib.BLL.BarCode().Update(bModel) == false)
            {
                return 0;
            }


            //修改storagePosition数据
            DataLib.Model.StoragePostion spmodel = new DataLib.BLL.StoragePostion().GetModel((int)bModel.storageid);
            spmodel.currvalume -= bModel.qty;
            spmodel.currweight -= bModel.nwt;
            new DataLib.BLL.StoragePostion().Update(spmodel);

            //插入storageData记录
            DataLib.Model.StorageData sdmodel = new DataLib.Model.StorageData();
            sdmodel.storageid = (int)bModel.storageid;
            sdmodel.inoutid = oModel.id;//
            sdmodel.barcodeid = bModel.id;
            sdmodel.InOrOut = (int)2;
            sdmodel.goodscode = bModel.goodscode;
            sdmodel.goodsName = bModel.goodsname;
            sdmodel.nwt = bModel.nwt;
            sdmodel.operDate = oModel.outStorageDate;
            sdmodel.storageno = spmodel.storagecode;
            sdmodel.operman = oModel.Operator;
            sdmodel.goodsid = new DataLib.BLL.Goods().GetgoodsID(sdmodel.goodscode);
            sdmodel.startNwt = new DataLib.BLL.StorageData().CurEndNwt(sdmodel.goodscode, sdmodel.storageno);
            //sdmodel.startNwt = CurEndNwt(sdmodel.goodscode, pdt.Rows[i]["storageno"].ToString());    //期初净重 
            sdmodel.endNwt = sdmodel.startNwt - sdmodel.nwt;
            if (new DataLib.BLL.StorageData().Add(sdmodel) > 0)
                return (decimal)bModel.nwt;
            return (decimal)0;
        }

        /// <summary>
        /// 2018年8月06日 
        /// </summary>
        /// <param name="cjoid"></param>
        /// <returns></returns>
        public string GetCumtomer(string loadnum, out string cumcode)
        {
            DataLib.Model.LoadNum lmodel = new DataLib.Model.LoadNum();

            if (loadnum.StartsWith("86"))
            {
                lmodel = new DataLib.BLL.LoadNum().GetLoadID(loadnum);
                cumcode = lmodel.cumcode;
            }
            else
            {
                cumcode = "";
                lmodel.cumname = "";
            }
            return lmodel.cumname;
        }


        /// <summary>
        /// 
        /// </summary>
        public void OperOutStorage(HttpContext context)
        {
            string oper = context.Request["oper"].ToString().Trim();
            int outid = int.Parse(context.Request["outid"].ToString().Trim());
            DataLib.BLL.OutStorage bll = new DataLib.BLL.OutStorage();
            DataLib.Model.OutStorage model = new DataLib.Model.OutStorage();

            string strbar = context.Request["outbar"].ToString().Trim();
            string strotype = context.Request["otype"].ToString().Trim();
            string outno = context.Request["outno"].ToString().Trim();
            string consumman = context.Request["ConsumMan"].ToString().Trim();
            string belong = context.Request["belong"].ToString().Trim();
            string graphic = context.Request["graphic"].ToString().Trim();

            model.id = outid;
            model.outStorageType = strotype;
            model.ConsumMan = consumman;
            model.belogarea = belong;
            model.graphicCity = graphic;


            if (outid == 0)
            {
                bll.Add(model);
            }
            else
            {
                bll.Update(model);
            }
        }

        /// <summary>
        /// 验证BarCode是否合法
        /// </summary>
        /// <param name="barcodevalue"></param>
        /// <param name="outType"></param>
        /// <returns>返回Json数组，Barcode、客户信息、验证结果</returns>
        public string OutBarCodeConfirm(string barcodevalue, string outType,string indepart,string outdepart,string oldload)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            //string isau = "0";
            //string strjson = "";
            //DataLib.Model.OutStorage outModel = new DataLib.Model.OutStorage();
            //DataLib.BLL.OutStorage outBll = new DataLib.BLL.OutStorage();
            //DataLib.Model.BarCode barModel = new DataLib.Model.BarCode();
            //DataLib.BLL.BarCode barBll = new DataLib.BLL.BarCode();

            //barModel = outBll.OutBarCodeConfirm(barcodevalue, outType,oldload, ref isau);
            //strjson += serializer.Serialize(barModel);
            //strjson += ",";
            //if (barModel != null && barModel.loadnumid != 0)    //2015年8月20日 17:37:16 原 if (barModel != null && barModel.cjoid != 0)
            //{
            //    strjson += GetCumtomer((int)barModel.loadnumid,barModel.loadnumv);
            //    if (indepart != null && outdepart != null && indepart != "" && outdepart != "")
            //    {
            //        if (indepart != barModel.barbelong)
            //        {
            //            isau = "归属地不同";
            //        }
            //        else if (outdepart != barModel.bargraphic)
            //        {
            //            isau = "处理地不同";
            //        }
            //        if ((outType == "5")
            //                  && oldload != null
            //                  && oldload != ""
            //                  && (barModel.loadnumv != oldload && oldload.Substring(0,2)=="86")
            //                  && (barModel.goodscode.Substring(0,1)=="D")
            //            )
            //        {
            //            isau = "不能多个Load同时移库";
            //        }
            //    }
            //}
            //else
            //{
            //    strjson += "{\"cumcode\":\"无\",\"cumname\":\"无\"}";
            //}
  
  
            //strjson += ",{\"isau\":\"" + isau + "\",\"indepart\":\"" + indepart + "\",\"outdepart\":\"" + outdepart + "\"}";
           
            //strjson = "[" + strjson + "]";
            EWMSWeb.Code.BarclodevValue bModel = EWMSWeb.Code.GetBarcodeValueData.GetBarcodeValues(barcodevalue, outType, oldload);
            if (bModel.isau == "OK")
            {
                if (bModel.mlist != null && bModel.mlist.Count > 0)
                {
                    foreach (DataLib.Model.BarCode b in bModel.mlist)
                    {
                        if (indepart != null && indepart.Trim() != "" && outdepart != null && outdepart.Trim() != "")
                        {
                            if (indepart != b.barbelong && indepart != null)
                            {
                                bModel.isau = "归属地不同";
                                break;
                            }
                            else if (outdepart != b.bargraphic && outdepart != null)
                            {
                                bModel.isau = "处理地不同";
                                break;
                            }
                            if ((outType == "5")
                                      && oldload != null
                                      && oldload != ""
                                      && (b.loadnumv != oldload && oldload.Substring(0, 2) == "86")
                                      && (b.goodscode.Substring(0, 1) == "D")
                                )
                            {
                                bModel.isau = "不能多个Load同时移库";
                                break;
                            }
                        }
                        else
                        {
                            indepart = b.barbelong;
                            outdepart = b.bargraphic;
                        }
                        if (oldload == null || oldload.ToString() == "")
                        {
                            oldload = b.loadnumv;
                        }
                    }
                    if (bModel.isau == null || bModel.isau.Trim() == "")
                    {
                        bModel.indepart = indepart;
                        bModel.outdepart = outdepart;
                        string cumcode = "";
                        bModel.cumname = GetCumtomer(oldload, out cumcode);
                        bModel.cumcode = cumcode;

                        bModel.isau = "OK";
                    }

                }
            }
            
            string strjson = serializer.Serialize(bModel);
           
            return strjson;
        }

        /// <summary>
        /// 获取出库单号，判断是否维护
        /// </summary>
        /// <param name="outtype1"></param>
        /// <param name="outid"></param>
        /// <returns></returns>
        public string GetOutStorageNo(object outtype1, object outid)
        {
            string strStorageNo = "";

            //根据分类出库方式生成出库编号
            DataLib.Model.OutStorage model = new DataLib.Model.OutStorage();

            string outtype = outtype1.ToString().Trim();
            if (outid != null && outid.ToString().Trim() != "" && outid.ToString().Trim() != "0")
            {
                model = new DataLib.BLL.OutStorage().GetModel(int.Parse(outid.ToString().Trim()));
                if (model.outStorageType == outtype)
                {
                    return model.outStorageNo;
                }
            }
            string strleft = "";
            switch (outtype)
            {
                case "1":
                    strleft = "C";
                    break;

                case "4":
                    strleft = "X";
                    break;
                case "3":
                    strleft = "S";
                    break;
                case "5":
                    strleft = "Y";
                    break;
                default:
                    strleft = "F";

                    break;
            }
            strStorageNo = Code.NumGeneration.GetSerialNum(strleft, "OutCode");
            return strStorageNo;
        }

        /// <summary>
        /// 获取出库是否成功
        /// </summary>
        /// <param name="arrbar"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public int SubmitOutStorage(string arrbar,DataLib.Model.OutStorage model)
        {
            int rowcount = -1;
            DataLib.BLL.OutStorage bll = new DataLib.BLL.OutStorage();
            rowcount = bll.OutStorageUpdate(model, arrbar);
            return rowcount;
        }

        /// <summary>
        /// Model对象传参
        /// </summary>
        /// <param name="arrbar"></param>
        /// <param name="outid"></param>
        /// <param name="outno"></param>
        /// <param name="oper"></param>
        /// <param name="belong"></param>
        /// <param name="graphicCity"></param>
        /// <param name="VLoadNum"></param>
        /// <param name="ConsumMan"></param>
        /// <param name="outStorageType"></param>
        /// <returns></returns>
        public int SaveOutStorage(object arrbar, object outid, object outno, object oper, object belong, object graphicCity, object ConsumMan, object saleno, object docusm, object outStorageType, object month, object remark)
        {
            int rowcount = -1;
            string ono = outno.ToString();

            string strbarr = "";
            if (arrbar != null)
            {
                strbarr = arrbar.ToString().Trim();
                if (strbarr.Length > 20 && strbarr.IndexOf(",") > 10)
                {
                    strbarr = strbarr.Remove(strbarr.Length - 1);
                }
            }
            if (outid != null)
            {
                DataLib.Model.OutStorage model = new DataLib.Model.OutStorage();
                DataLib.BLL.OutStorage bll = new DataLib.BLL.OutStorage();
                int outstrid = int.Parse(outid.ToString());
                if (outstrid != 0)
                {
                    model = bll.GetModel(outstrid);
                 }
                else
                {
                    model.id = 0;
                }
                model.outStorageNo = GetOutStorageNo(outStorageType, outid);
                model.Operator = oper.ToString();
                model.belogarea = belong.ToString();
                model.graphicCity = graphicCity.ToString();
                model.ConsumMan = ConsumMan.ToString();
                model.outStorageType = outStorageType.ToString();
                model.clearmonth = month.ToString();
                model.memo = remark.ToString();
                if (docusm != null)
                {
                    model.DoCustomer = docusm.ToString();
                }
                if (saleno != null)
                {
                    model.OutsNo = saleno.ToString();
                }
               

              
                rowcount = SubmitOutStorage(strbarr, model);

            }
            return rowcount;
        }

        public string GetBarcodeValueArr(string arrbarid)
        {
            string str = "";
            if (arrbarid != "")
            {
                string strtemp = arrbarid.Remove(arrbarid.Length - 1);
                DataTable dt = new DataTable();
                dt = new DataLib.BLL.BarCode().GetBarCodeValue(strtemp);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        str += dt.Rows[i]["barcodevalue"].ToString();
                        str += ",";
                    }
                    str = str.Remove(str.Length - 1);
                }
            }
            return str;
        }

        public int DelBarCode(string barvalue, string operman, string outid)
        {
            int rows = 0;
            DataLib.BLL.OutStorage bll = new DataLib.BLL.OutStorage();
            rows = bll.DelBarOut(barvalue, operman, outid);
            return rows;
        }
    }
}